package com.he.security.web.reactive.result;

import com.he.security.core.annotation.CurrentSecurityContext;
import com.he.security.core.context.ReactiveSecurityContextHolder;
import com.he.security.core.context.SecurityContext;
import org.reactivestreams.Publisher;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumentResolverSupport {

    private ExpressionParser parser = new SpelExpressionParser();

    private BeanResolver beanResolver;

    public CurrentSecurityContextArgumentResolver(ReactiveAdapterRegistry adapterRegistry) {
        super(adapterRegistry);
    }

    public void setBeanResolver(BeanResolver beanResolver) {
        Assert.notNull(beanResolver, "beanResolver cannot be null");
        this.beanResolver = beanResolver;
    }
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return findMethodAnnotation(CurrentSecurityContext.class, parameter) != null;
    }

    @Override
    public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
        ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType());
        Mono<SecurityContext> reactiveSecurityContext = ReactiveSecurityContextHolder.getContext();
        if (reactiveSecurityContext == null) {
            return null;
        }
        return reactiveSecurityContext.flatMap(a -> {
            Object p = resolveSecurityContext(parameter, a);
            Mono<Object> o = Mono.justOrEmpty(p);
            return adapter == null ? o : Mono.just(adapter.fromPublisher(o));
        });
    }

    private Object resolveSecurityContext(MethodParameter parameter, SecurityContext securityContext) {
        CurrentSecurityContext securityContextAnnotation = findMethodAnnotation(CurrentSecurityContext.class, parameter);
        Object securityContextResult = securityContext;
        String expressionToParse = securityContextAnnotation.expression();
        if (StringUtils.hasLength(expressionToParse)) {
            StandardEvaluationContext context = new StandardEvaluationContext();
            context.setRootObject(securityContext);
            context.setVariable("this", securityContext);
            context.setBeanResolver(beanResolver);
            Expression expression = this.parser.parseExpression(expressionToParse);
            securityContextResult = expression.getValue(context);
        }

        if (isInvalidType(parameter, securityContextResult)) {
            if (securityContextAnnotation.errorOnInvalidType()) {
                throw new ClassCastException(securityContextResult + " is not assignable to "
                        + parameter.getParameterType());
            } else {
                return null;
            }
        }

        return securityContextResult;
    }

    private boolean isInvalidType(MethodParameter parameter, Object reactiveSecurityContext) {
        if (reactiveSecurityContext == null) {
            return false;
        }
        Class<?> typeToCheck = parameter.getParameterType();
        boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType());
        if (isParameterPublisher) {
            ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
            Class<?> genericType = resolvableType.resolveGeneric(0);
            if (genericType == null) {
                return false;
            }
            typeToCheck = genericType;
        }
        return !typeToCheck.isAssignableFrom(reactiveSecurityContext.getClass());
    }


    private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
        T annotation = parameter.getParameterAnnotation(annotationClass);
        if (annotation != null) {
            return annotation;
        }
        Annotation[] annotationsTosSearch = parameter.getParameterAnnotations();
        for (Annotation toSearch : annotationsTosSearch) {
            annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
            if (annotation != null) {
                return annotation;
            }
        }
        return null;
    }


}
